Labels: Names used to label loops and control flow

Labels in Node.js (and JavaScript) are used to name a statement, typically for controlling the flow of loops or conditional statements. Labels can be particularly useful for breaking out of or continuing a specific loop when you have nested loops.


outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      break outerLoop; // Exits the outer loop when j equals 1
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}

Here outer for loop is given a Label.

Usage in break and continue: Labels are used with break or continue to exit or skip specific loops. They are most commonly used in nested loops.

Label outerLoop: Marks the outer loop.

break outerLoop;: Exits the outerLoop when j equals 1, skipping any further iterations of the outer loop.

You Might Also Like

Destructuring Props in Functional Components

When you pass any props to any componenet, as in this example passing name and age as props to Profi...

Simplify Context Usage with a Custom Hook

Instead of using useContext directly every time, create a custom hook: **1. Define the Context and...